<template>
  <div class="order-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>订单管理</h1>
          <div class="header-actions">
            <el-button @click="loadOrders" :loading="loading">刷新</el-button>
          </div>
        </div>

        <el-card>
          <div class="toolbar">
            <el-select
              v-model="statusFilter"
              placeholder="按状态筛选"
              clearable
              @change="loadOrders"
            >
              <el-option label="全部" value="" />
              <el-option label="待付款" :value="0" />
              <el-option label="待发货" :value="1" />
              <el-option label="运输中" :value="2" />
              <el-option label="已完成" :value="3" />
              <el-option label="已取消" :value="4" />
              <el-option label="申请退货" :value="5" />
              <el-option label="已退货" :value="6" />
            </el-select>
            <el-button :disabled="!selected.length" @click="batchShip">批量设为已发货</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table :data="orders" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="订单号" prop="orderSn" width="180" />
            <el-table-column label="用户ID" prop="userId" width="80" />
            <el-table-column label="收货人" prop="receiverName" width="100" />
            <el-table-column label="收货电话" prop="receiverPhone" width="120" />
            <el-table-column label="总金额" prop="totalAmount" width="100">
              <template #default="{ row }"> ¥{{ row.totalAmount }} </template>
            </el-table-column>
            <el-table-column label="实付金额" prop="payAmount" width="100">
              <template #default="{ row }"> ¥{{ row.payAmount }} </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdAt" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button size="small" @click="viewOrder(row)">查看</el-button>
                <el-button size="small" type="primary" @click="updateStatus(row)"
                  >更新状态</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { orderService } from '@/api/orderService'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createLogger } from '@/utils/logger'

type OrderRow = {
  orderId: number
  orderSn: string
  userId: number
  totalAmount: number
  payAmount: number
  status: number
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  createdAt: string
  updatedAt: string
}

const orderLogger = createLogger('OrderManage')

const loading = ref(false)
const orders = ref<OrderRow[]>([])
const selected = ref<OrderRow[]>([])
const statusFilter = ref<number | string>('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const loadOrders = async () => {
  loading.value = true
  try {
    const page = currentPage.value
    const size = pageSize.value
    const status = statusFilter.value !== '' ? Number(statusFilter.value) : undefined

    orderLogger.debug('开始加载订单，参数:', { page, size, status })
    const res = await orderService.getOrdersList(page, size, status)
    orderLogger.debug('API响应数据:', res.data)

    // 统一处理不同的响应格式
    let responseData: unknown = null
    let ordersList: unknown[] = []
    let totalCount = 0

    if (res.data) {
      // 格式1: { code: 200, msg: "查询成功", data: { orders: [...], total: 123 } }
      if (res.data.code === 200 && res.data.data) {
        responseData = res.data.data
        const data = res.data.data as unknown as Record<string, unknown>
        ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
        totalCount = (data.total as number) || 0
      }
      // 格式2: { success: true, data: { orders: [...], total: 123 } }
      else if ('success' in res.data && res.data.success === true && 'data' in res.data && res.data.data) {
        responseData = res.data.data
        const data = res.data.data as unknown as Record<string, unknown>
        ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
        totalCount = (data.total as number) || 0
      }
      // 格式3: 直接返回数据数组
      else if (Array.isArray(res.data)) {
        ordersList = res.data
        totalCount = res.data.length
      }
      // 格式4: 直接返回数据对象
      else if (typeof res.data === 'object' && res.data !== null) {
        const data = res.data as unknown as Record<string, unknown>
        if (data.orders || data.list) {
          ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
          totalCount = (data.total as number) || ordersList.length
        }
      }
    }

    orderLogger.debug('解析后的订单数据:', {
      ordersList,
      totalCount,
      responseData
    })

    if (ordersList.length > 0) {
      // 确保数据格式正确，处理后端返回的Order实体结构
      orders.value = ordersList.map((order: unknown) => {
        // 处理可能的嵌套结构
        const orderObj = order as Record<string, unknown>
        const orderData = (orderObj.order as Record<string, unknown>) || orderObj
        
        return {
          orderId: Number(orderData.orderId || orderData.id || orderObj.orderId || 0),
          orderSn: String(orderData.orderSn || orderData.orderNumber || orderObj.orderSn || ''),
          userId: Number(orderData.userId || orderData.user_id || orderObj.userId || 0),
          totalAmount: Number(orderData.totalAmount || orderData.total_amount || orderObj.totalAmount || 0),
          payAmount: Number(orderData.payAmount || orderData.pay_amount || orderObj.payAmount || 0),
          status: Number(orderData.status || orderObj.status || 0),
          receiverName: String(orderData.receiverName || orderData.receiver_name || orderObj.receiverName || ''),
          receiverPhone: String(orderData.receiverPhone || orderData.receiver_phone || orderObj.receiverPhone || ''),
          receiverAddress: String(orderData.receiverAddress || orderData.receiver_address || orderObj.receiverAddress || ''),
          createdAt: String(orderData.createdAt || orderData.created_at || orderObj.createdAt || ''),
          updatedAt: String(orderData.updatedAt || orderData.updated_at || orderObj.updatedAt || ''),
        }
      })
    } else {
      orders.value = []
    }
    
    total.value = totalCount
    orderLogger.debug('最终订单数据:', orders.value)
  } catch (error) {
    orderLogger.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请检查网络连接')
    orders.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const viewOrder = (order: OrderRow) => {
  ElMessageBox.alert(
    `订单号: ${order.orderSn}\n收货人: ${order.receiverName}\n电话: ${order.receiverPhone}\n地址: ${order.receiverAddress}\n总金额: ¥${order.totalAmount}\n实付金额: ¥${order.payAmount}`,
    '订单详情',
    {
      confirmButtonText: '确定',
    },
  )
}

const updateStatus = async (order: OrderRow) => {
  try {
    const { value } = await ElMessageBox.prompt(
      '请输入新的状态值 (0:待付款, 1:待发货, 2:运输中, 3:已完成, 4:已取消)',
      '更新订单状态',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-6]$/,
        inputErrorMessage: '状态值必须是0-6之间的数字',
      },
    )

    await orderService.updateOrderStatus(order.orderId, parseInt(value))
    ElMessage.success('状态更新成功')
    await loadOrders()
  } catch (e) {
    if (e !== 'cancel') {
      orderLogger.error('更新订单状态失败', e)
      ElMessage.error('更新订单状态失败')
    }
  }
}

const handleSelectionChange = (rows: OrderRow[]) => {
  selected.value = rows
}

const batchShip = async () => {
  if (!selected.value.length) return

  try {
    await ElMessageBox.confirm('确定要将选中的订单设为已发货吗？', '批量操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await Promise.all(selected.value.map((o) => orderService.updateOrderStatus(o.orderId, 2)))
    selected.value = []
    ElMessage.success('批量操作成功')
    await loadOrders()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  }
}

const batchDelete = async () => {
  if (!selected.value.length) return

  try {
    await ElMessageBox.confirm('确定要删除选中的订单吗？此操作不可恢复！', '批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await Promise.all(selected.value.map((o) => orderService.deleteOrder(o.orderId)))
    selected.value = []
    ElMessage.success('批量删除成功')
    await loadOrders()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadOrders()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadOrders()
}

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待付款',
    1: '待发货',
    2: '运输中',
    3: '已完成',
    4: '已取消',
    5: '申请退货',
    6: '已退货',
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status: number) => {
  const typeMap: Record<number, '' | 'success' | 'info' | 'warning' | 'danger'> = {
    0: 'warning',
    1: 'info',
    2: 'info',
    3: 'success',
    4: 'danger',
    5: 'warning',
    6: 'info',
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  border-radius: 8px;
  
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-card) {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 24px;
}
</style>
